<template>
  <div class="content">
    <el-form ref="form" :model="form" label-width="80px" :inline="true">

      <el-form-item>
        <el-select
          clearable
          v-model="form.deptId"
          placeholder="请选择所属学校"
          size="mini"
          style="width:150px"
        >
          <el-option :label="item.name" :value="item.id" v-for="item in schoolList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input clearable v-model="form.name" size="mini" placeholder="请输入姓名" style=" width:150px "></el-input>
      </el-form-item>

      <!--订单编号-->
      <el-form-item>
        <el-input clearable v-model="form.number" size="mini" placeholder="请输入订单编号" style="width:150px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select clearable v-model="form.status" placeholder="请选择状态" size="mini" style="width:150px">
          <el-option label="待审核" value="0"></el-option>
          <el-option label="待打款" value="1"></el-option>
          <el-option label="审核失败" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select clearable v-model="form.type" placeholder="用户类型" size="mini" style="width:150px">
          <el-option label="学生" value="1"></el-option>
          <el-option label="老师" value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" size="mini" class="btn" @click="search"><i class="fa fa-search"
                                                                           style="margin-right:5px;"></i>查询
      </el-button>
    </el-form>

    <!-- <el-divider></el-divider> -->
    <template>
      <el-table :row-key="getRowKeys"
                :expand-row-keys="expands"
                @expand-change="getClass"
                :data="tableData"
                v-loading="loading"
                size="mini"
                style="width: 100%;margin-top:30px"
      >

        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              border
              size="mini"
              v-loading="loading1"
              :data="tableDataDetail"
              style="width: 100%">
              <el-table-column
                prop="createBy"
                label="处理人">
              </el-table-column>
              <el-table-column
                prop="lastUpdateTime"
                label="处理时间">
              </el-table-column>
              <el-table-column
                prop="remark"
                label="处理结果">
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="退款ID" width="80">
           <template slot-scope="scope">
            <span v-show="scope.row.status==0">
              <el-badge value="new" class="item">
                <div class="idbtn">{{scope.row.id}}</div>
              </el-badge>
            </span>
             <span v-show="scope.row.status!=0">
                <div class="idbtn">{{scope.row.id}}</div>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="订单编号"></el-table-column>
        <el-table-column prop="username" label="用户姓名"></el-table-column>
        <el-table-column prop="type" label="退款类型">
          <template slot-scope="scope">
            <span v-show="scope.row.type==1">注销退款</span>
            <span v-show="scope.row.type==2">消费退款</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="打款姓名">
          <template slot-scope="scope">
            <span >{{scope.row.name||"--"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bankName" label="银行"></el-table-column>
        <el-table-column prop="bankNo" label="银行卡号"></el-table-column>
        <el-table-column prop="depositBankName" label="开户行"></el-table-column>

<!--        <el-table-column prop="classId" label="年级"></el-table-column>-->
<!--        <el-table-column prop="unit" label="班级"></el-table-column>-->
        <el-table-column prop="userType" label="用户类型"></el-table-column>

        <el-table-column prop="remark" label="退款理由">
          <template slot-scope="scope">
            <span >{{scope.row.remark||"--"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="refundAmt" label="退款金额（元）"></el-table-column>

        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span v-show="scope.row.status==0">
              <el-badge is-dot class="item">
                待审批
              </el-badge>
            </span>
            <span v-show="scope.row.status==1">待打款</span>
            <span v-show="scope.row.status==2">审核失败</span>
            <span v-show="scope.row.status==3">已完成</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" :label="$t('action.operation')" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              v-show="scope.row.status==0"
              @click="editAddOrUpdate(scope.$index, scope.row.id)"
            ><i class="fa fa-edit" style="margin-right:5px;"></i>审批处理
            </el-button>
            <el-button
              size="mini"
              v-show="scope.row.status==1"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            ><i class="fa fa-trash" style="margin-right:5px;"></i>退款
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>
    <el-row>
      <el-col :span="24">
        <el-pagination
          style="float:right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 15, 20,50,100]"
          :page-size="everyPageNum"
          layout="total, sizes,prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
        <div class="grid-content bg-purple-dark" style="font-size:13px;float:right;margin:26px 0 0 10px">合计金额：<span
          style="color:rgb(20, 136, 154);font-weight:bold">{{sumData}}</span></div>
      </el-col>
    </el-row>

    <!--新增编辑弹框-->
    <el-dialog :title="updateStatus==1?'审批处理':'审批处理'" :visible.sync="showEdit" width="60%" v-dialogDrag>
      <editStudent @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></editStudent>
    </el-dialog>

  </div>
</template>

<script>
  import Cookies from 'js-cookie'
  import editStudent from '@/components/Refund/index'


  export default {
    name: 'StudentManagement',
    components: {
      editStudent,
    },
    data() {
      return {
        tableDataDetail: [],

        getRowKeys(row) {
          return row.id;
        },
        expands: [],
        loading1:false,

        uploadId: '',//上架id

        tableData1: [],
        url: this.$Config.url,
        showEdit: false, //显示编辑弹框
        updateStatus: 1, //默认是新增
        loading: false,
        deptId: '', //学校id
        total: 1, //总页数
        everyPageNum: 10, //每页多少条
        currentPage: 1, //当前页
        form: {
          number:"",
          name:"",
          status: '0',
          deptId: '',
          type:""
        },
        tableData: [],
        gradeData: [], //年级列表
        classData: [], //班级列表
        schoolList: [], //学校数据
        requestHeader: {
          'x-baie-admin-token': Cookies.get('token')
        },
        disableSchool: false,
        sumData: ''
      }
    },
    mounted() {
      this.getSchool()
      const userInfo = JSON.parse(localStorage.getItem('userInfo')).deptId
      if (userInfo == null || userInfo == '') {
        this.disableSchool = false
      } else {
        this.form.deptId = userInfo
        this.disableSchool = true
        this.gradeList(userInfo)
      }
      this.common();
    },
    methods: {
      getClass(row, expandedRows) {
        const that = this;
        // that.gradeId = row.id;

        that.expandedRows = expandedRows;
        if (expandedRows.length) {
          that.expands = [];
          if (row) {
            that.expands.push(row.id); // 每次push进去的是每行的ID
          }
        } else {
          that.expands = []; // 默认不展开
        }

        that.everyClass(row.id);
      },
      everyClass(refundorderfId){
        const that=this;
        that.loading1 = true;
        this.$axios
          .get(that.url + "/refundorderflow/list", {
            params: {
              refundorderfId
            },
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          })
          .then(function(res) {
            that.loading1 = false;
            if(res.data.code == 200){
              that.tableDataDetail=res.data.data
            }else{
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          }).catch(error=>{
          that.loading1 = false;
        })
      },
      uploadFood(index, id) {
        this.uploadId = id
        this.showUpload = true//让上传显示
      },
      getSchool() {
        const that = this
        this.$axios
          .get(that.url + '/admin/dept/list', {
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.schoolList = res.data.data
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      downLoadDemo() {
        const deptId = JSON.parse(localStorage.getItem('userInfo')).deptId
        var divFrame = window.parent.document.getElementById(
          'downLoadListFrame'
        )
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame)
        }
        var iframe = window.parent.document.createElement('iframe')
        iframe.setAttribute('id', 'downLoadListFrame')
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe)
        divFrame = window.parent.document.getElementById('downLoadListFrame')
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = this.url + '/admin/excel/student?deptId=' + deptId
        divFrame.style.display = 'none'

      },
      excelExport() {
        const deptId = JSON.parse(localStorage.getItem('userInfo')).deptId
        // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
        var divFrame = window.parent.document.getElementById(
          'downLoadListFrame'
        )
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame)
        }
        var iframe = window.parent.document.createElement('iframe')
        iframe.setAttribute('id', 'downLoadListFrame')
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe)
        divFrame = window.parent.document.getElementById('downLoadListFrame')
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = `${this.url}/admin/student/export?name=${this.form.statusChecked == 1 ? this.form.statusValue : ''}&studentNo=${this.form.statusChecked == 2 ? this.form.statusValue : ''}&idNo=${this.form.statusChecked == 3 ? this.form.statusValue : ''}&status=${this.form.status}&gradeId=${this.form.glassId}&classId=${this.form.classId}&phone=${this.form.phone}`
        divFrame.style.display = 'none'

      },
      uploadSuccess(response, file, fileList) {
        if (response.code == 200) {
          this.$message({
            message: '导入成功',
            type: 'success'
          })
          this.common(this.currentPage, this.everyPageNum)
        } else {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        }
      },
      handlePreview(file) {
        console.log(file)
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${
            files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        )
      },
      gradeList(id) {
        const that = this
        this.$axios
          .get(that.url + '/admin/grade/list', {
            params: {
              deptId: id
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.gradeData = res.data.data
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      classList(id) {
        const that = this
        that.form.classId = ''
        this.$axios
          .get(that.url + '/admin/class/list', {
            params: {
              gradeId: id
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.classData = res.data.data
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      search() {
        this.common(this.currentPage, this.everyPageNum)
      },
      handleDelete(index, row) {
        this.$confirm('退款金额：￥'+row.refundAmt, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteStudent(row.id)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      deleteStudent(refundOrdreId) {
        const that = this
        this.$axios
          .post(
            that.url + '/refundorder/success',
            that.$qs.stringify({ refundOrdreId }),
            {
              headers: {
                'x-baie-admin-token': Cookies.get('token')
              }
            }
          )
          .then(function(res) {
            if (res.data.code == 200) {
              that.$message({
                type: 'success',
                message: '退款成功!'
              })
              that.common(that.currentPage, that.everyPageNum)
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      editAddOrUpdate(status, id) {

        //新增或编辑
        /**
         * 1是新增
         * 2是编辑
         */
        this.showEdit = true

        setTimeout(() => {
          this.$refs['child'].resetData(id)
        }, 0)

      },
      handleSizeChange(val) {
        //   每页多少条
        this.everyPageNum = val
        this.common(this.currentPage, val)
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.common(val, this.everyPageNum)
      },
      hideEditStatus(status) {
        this.showEdit = false
        this.common(this.currentPage, this.everyPageNum)
      },
      common(pageNo = 1, pageSize = 10) {
        const that = this
        const deptId = JSON.parse(localStorage.getItem('userInfo')).deptId
        that.loading = true
        this.$axios
          .get(that.url + '/refundorder/page', {
            params: {
              pageNo,
              pageSize,
              number:this.form.number,
              userType:this.form.type,
              name:this.form.name,
              status:this.form.status,
              deptId: (deptId == null ? this.form.deptId : deptId)
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            that.loading = false
            if (res.data.code == 200) {
              that.tableData = res.data.data.records
              that.total = res.data.data.total
              that.sumData = res.data.sum
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            that.loading = false
            console.log(error)
          })
      },
      handleClick(row) {
        console.log(row)
      }
    }
  }
</script>

<style scoped lang="scss">
  .upload {
    display: inline-block;
  }
  .idbtn{
    border: none;
    height: 30px;
    width: 30px;
  }
  .el-pagination {
    float: right;
    margin: 20px 10px;
  }

  .button_list {
    margin-bottom: 10px;
  }

  .content {
    text-align: left;
  }

  .el-divider {
    margin: 10px 0;
  }

  .btn {
    margin-top: 6px;
  }

  .el-form-item {
    margin-bottom: 0;
  }
  .item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
